/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.cslg.news.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.mail.EmailException;

import cn.cslg.news.db.DBPoolException;
import cn.cslg.news.service.UserService;

/**
 *
 * @author jimshen
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

	private static final long serialVersionUID = 4140085922348686388L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException, UnsupportedEncodingException {
		String username = req.getParameter("username");
		String truename = req.getParameter("truename");
		String password = req.getParameter("password");
		String email = req.getParameter("email");

		// truename=new String(truename.getBytes("iso-8859-1"),"utf-8");
		// System.out.println(truename);
		resp.setContentType("text/html;charset=utf-8");
		UserService us = new UserService();
		us.setBaseUrl((String) req.getServletContext().getAttribute("ContextPath"));
		try {
			boolean res = us.insertUser(username, truename, password, email);

			if (res) {
				try (PrintWriter out = resp.getWriter()) {
					out.print("注册成功");
					out.flush();
				}
			} else {
				try (PrintWriter out = resp.getWriter()) {
					out.print("注册失败");
					out.flush();
				}
			}
		} catch (SQLException | DBPoolException | NamingException | EmailException ex) {
			throw new ServletException(ex);
		}
	}

}
